<template>
  <div class="login-container">
    <img class="background-img" src="./image/loginBg.png" />
    <div class="title-box">
<!--      <img src="./image/logo_login@2x.png" class="title-image" alt="">-->
    </div>
    <div class="login-bg">
<!--      <div class="login-title">政校会易登录</div>-->

      <div class="title-container">
        <span @click="loginMethods('password')" :class="isPhoneLogin?'title': 'title actived'">密码登录</span>
<!--        <span @click="loginMethods('phone')" :class="isPhoneLogin?'title actived': 'title'">验证码登录</span>-->
      </div>
      <div class="title-line" />

      <el-form
        ref="loginForm"
        :model="loginForm"
        class="login-form"
        label-position="left"
      >
        <el-row v-if="!isPhoneLogin">
          <el-col :span="24">
            <el-form-item>
              <el-input
                ref="phone"
                v-model="loginForm.username"
                placeholder="请输入用户名"
                type="text"
                class="login-input"
                @keyup.enter.native="handleLogin"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="isPhoneLogin">
          <el-col :span="24">
            <el-form-item>
              <el-input
                ref="phone"
                v-model="loginForm.phone"
                placeholder="请输入手机号"
                type="text"
                class="login-input"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="isPhoneLogin">
          <el-col :span="14">
            <el-form-item prop="password">
              <el-input
                ref="password"
                v-model="loginForm.code"
                placeholder="请输入验证码"
                type="text"
                class="login-input"
                @keyup.enter.native="handleLogin"
              >

              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4" :offset="1">
            <el-button
              style="width: 114px;position: relative;top: 4px;"
              type="primary"
              :disabled="!canSendSNSStatus"
              @click="sendCode"
            >
              {{ codeText }}
            </el-button>
          </el-col>
        </el-row>

        <el-row v-else>
          <el-form-item prop="password">
            <el-input
              ref="password"
              v-model="loginForm.password"
              placeholder="请输入密码"
              :type="passwordType"
              class="login-input"
              @keyup.enter.native="handleLogin"
            >
              <template slot="suffix">
                <i class="el-input__icon el-icon-view" @click="showPwd" />
              </template>
            </el-input>
          </el-form-item>
        </el-row>

        <el-row :gutter="15">
          <el-col :span="24" style="text-align: center">
            <el-button
              :loading="loading"
              type="primary"
              style="width: 100%; margin-bottom: 30px"
              :disabled="!isCanclick"
              @click.native.prevent="handleLogin"
            >
              登录
            </el-button>
          </el-col>
<!--          <el-col :span="12" style="text-align: center">-->
<!--            <el-button-->
<!--              :loading="loading"-->
<!--              type="primary"-->
<!--              style="width: 100%; margin-bottom: 30px"-->
<!--              :disabled="!isCanclick"-->
<!--              @click.native.prevent="goToRegister"-->
<!--            >-->
<!--              去授权-->
<!--            </el-button>-->
<!--          </el-col>-->

          <div class="login-panel-footer">
            <div>
              <el-checkbox-group
                v-model="autoLogin"
                fill="005c3f"
                text-color="005c3f"
                @change="changeAutoLogin"
              >
                <el-checkbox :label="isAutoLogin">
                  下次自动登录
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <div
              class="link-color"
              type="primary"
              @click="goToForget"
            >忘记密码</div>
          </div>
        </el-row>
      </el-form>
    </div>
    <div class="float-header-logo"></div>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import validate from "@/validate/login";
import md5 from "js-md5";
import {target} from '@/utils/config'
import * as service from "./service";
export default {
  name: "Login",
  components: {},
  data() {
    return {
      activeName: "first",
      codeKey: "",
      snsKey: "",
      loginForm: {
        snsCode: "",
        code: "",
        username: "",
        loginType: "0", // 登录类型,1、验证码；2、密码
        password: "",
      },
      passwordType: "password",
      loading: false,
      loginRules: validate,
      isPhoneLogin: false, // false : 账号密码登录(默认),true : 手机号登录
      redirect: undefined,
      otherQuery: {},
      codeText: "发送验证码",
      disabled: false,
      isCanclick: true,
      isAutoLogin: true,
      autoLogin: [],
      target: "users",
      codeImage: "",
      intervalSeconds: 0,
      canSendSNSStatus: true,
      timer: {},
      verifyCodeVal: "",
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
    isPhoneLogin: function (newVal) {
      this.loginForm.password = "";
      return newVal
        ? (this.loginRules.password[0].message = "请输入验证码")
        : (this.loginRules.password[0].message = "请输入密码");
    },
  },
  created() {},
  mounted() {
    // if (this.loginForm.phone === '') {
    //   this.$refs.phone.focus()
    // } else if (this.loginForm.password === '') {
    //   this.$refs.password.focus()
    // }
    this.target = target
    if (Cookies.get("isAutoLogin") === "true") {
      this.autoLogin = [true];
      this.loginForm.username = Cookies.get("username");
      this.loginForm.password = Cookies.get("password");
    }
    if (Cookies.get("isAutoLogin") === "false") {
      this.autoLogin = [];
    }
  },
  destroyed() {
    clearInterval(this.timer);
  },
  methods: {
    goToForget() {
      const target = this.target
      this.$router.push(`/forget?target=${target}`)
    },
    loginMethods(type) {
      if(type === 'phone') {
        this.isPhoneLogin = true
      } else {
        this.isPhoneLogin = false
      }
    },
    changeVerifyCode() {
      if (this.target) {
        this.getSupplierVerifyCode();
      } else {
        this.getVerifyCode();
      }
    },
    setRefreshCode() {
      if (this.timer) {
        clearInterval(this.timer);
      }
      this.timer = setInterval(() => {
        if (this.target) {
          this.getSupplierVerifyCode();
        } else {
          this.getVerifyCode();
        }
      }, 1000 * 60);
    },
    getSupplierVerifyCode() {
      service.verificationSupplierCode({}).then((res) => {
        console.log("res.data ---", res.data);
        this.codeImage = res.data.url;
        this.codeKey = res.data.key;
        this.verifyCodeVal = res.data.value;
      });
    },
    getVerifyCode() {
      service.verificationCode({}).then((res) => {
        console.log("res.data ---", res.data);
        this.codeImage = res.data.url;
        this.codeKey = res.data.key;
        this.verifyCodeVal = res.data.value;
      });
    },
    handleClick(tab) {
      if (this.target) {
        this.getSupplierVerifyCode();
      } else {
        this.getVerifyCode();
      }
      this.loginForm.code = "";
      this.loginForm.snsCode = "";
      this.loginForm.username = "";
      this.loginForm.password = "";
      this.loginForm.loginType = tab.index;
    },
    changeAutoLogin(val) {
      if (val.length > 0) {
        Cookies.set("isAutoLogin", true);
      } else {
        Cookies.set("isAutoLogin", false);
      }
    },
    sendCode() {
      if (!this.canSendSNSStatus) {
        return;
      }
      const params = {
        phone: this.loginForm.phone,
        type: 1,
      };

      const target = this.target
      if(target === 'platform') {
        params.userType = 4
      } else if(target === 'users') {
        params.userType = 6
      }

      if (params.phone === "") {
        this.$message.error("请输入手机号");
        return;
      }
      if (!/^1[3456789]\d{9}$/.test(params.phone)) {
        this.$message.error("请输入正确的手机号");
        return;
      }
      service.sendSmsCode(params).then((res) => {
        this.snsKey = res.data.key;
        this.$message.success("发送成功");
        this.canSendSNSStatus = false;
        this.startIntervalSecond();
      });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    startIntervalSecond() {
      this.intervalSeconds = 60;
      let timer = setInterval(() => {
        this.intervalSeconds -= 1;
        this.codeText = this.intervalSeconds
        if (this.intervalSeconds <= 0) {
          this.canSendSNSStatus = true;
          this.codeText = '发送验证码'
          clearInterval(timer);
        }
      }, 1000);
    },
    goToRegister() {
      console.log('去注册')
      this.$router.push("/register")
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          // this.loginForm.loginType = this.isPhoneLogin ? 2 : 1 // 判断账号密码登录还是验证码登录

          this.$store.dispatch('user/logout')
          this.loading = true;
          if (this.autoLogin.length > 0) {
            Cookies.set("username", this.loginForm.username);
            Cookies.set("password", this.loginForm.password);
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
          }
          const params = JSON.parse(JSON.stringify(this.loginForm));
          // console.log('md5 ---', md5('e10adc3949ba59abbe56e057f20f883e'))
          params.password = md5(params.password);

          // console.log("md5 ---", md5(params.password));
          params.target = this.target
          // params.key = this.codeKey
          // params.smsKey = this.snsKey
          params.isPhoneLogin = this.isPhoneLogin
          console.log('params ---', params)

          this.$store
            .dispatch("user/login", params)
            .then(() => {
              this.$message.success("登录成功");
              this.getIsAccess().then((childRes) => {
                // 0未激活
                if(childRes == 0 || childRes == 2) {
                  this.$router.replace('/register')
                } else {
                  setTimeout(() => {
                    this.loading = false;
                    window.location.href = "/";
                    // this.$router.replace('/')
                  }, 1000);
                }
              })
            })
            .catch((err) => {
              console.log("登录异常", err);
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 获取判断是否授权
    getIsAccess() {
      return new Promise((reslove, reject) => {
        service.getIsAccess({}).then((res) => {
          reslove(res.data)
          window.localStorage.setItem('isAccess', res.data)
        })
      })
    }
  },
};
</script>

<style lang="scss">
.login-container {
  height: 100%;
  width: 100%;
  .background-img {
    position: absolute;
    z-index: -99;
    height: 100%;
    width: 100%;
  }
  .company-logo {
    position: absolute;
    left: 20%;
    top: 10%;
    display: flex;
    align-items: center;
    .logo-img {
      width: 100px;
      height: 100px;
    }
    .company-name {
      margin-left: 50px;
      font-size: 28px;
      color: rgb(22, 97, 141);
      font-weight: bold;
    }
  }
  .title-container {
    text-align: center;
    color: #909399;
    font-size: 14px;
    padding: 15px 0;
    display: flex;
    .title{
      width: 50%;
      cursor: pointer;
    }
    .actived {
      color: #E61224;
    }
  }
  .login-form {
    width: 300px;
    margin: 0 auto;
    .title-container {
      text-align: center;
      color: #E61224;
      font-size: 14px;
      padding: 0 0 30px 0;
    }
    .title-line {
      width: 100%;
      height: 1px;
      background: #eeeeee;
      margin-bottom: 25px;
    }
  }
  .title-line {
    width: 100%;
    height: 1px;
    background: #eeeeee;
    margin-bottom: 25px;
  }
  .login-bg {
    position: absolute;
    top: 250px;
    left: 50%;
    margin-left: -200px;
    width: 400px;
    height: 320px;
    border-radius: 10px;
    background: white;
  }
}

.el-input__inner {
  //background: #F4F4F4!important;
}
.login-panel-footer {
  position: absolute;
  bottom: -10px;
  display: flex;
  justify-content: space-between;
  width: 100%;
  align-items: center;
}
.el-checkbox__input.is-checked + .el-checkbox__label {
  color: #E61224 !important;
}
.el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #E61224 !important;
  border-color: #E61224 !important;
}
.link-color {
  color: #E61224;
  font-size: 14px;
  font-weight: bold;
  cursor: pointer;
}
.float-header-logo {
  top: 63px;
  position: absolute;
  left: 50%;
  margin-left: -75px;
  text-align: center;

  .logo-image {
    width: 150px;
  }
  .sub-title {
    position: relative;
    left: 20px;
    text-align: center;
    font-size: 12px;
    color: white;
    margin-top: 10px;
  }
}

.code-box {
  position: absolute;
  right: -10px;
  top: 4px;
  img {
    width: 80%;
  }
}

.get-code-input {
  ::v-deep input {
    width: 200px;
  }
}
.login-title {
  padding: 15px;
  text-align: center;
  border-bottom: 1px solid #dcdfe6;
  margin-bottom: 30px;
}

.title-box {
  width: 100%;
  text-align: center;
  position: absolute;
  top: 150px;
}
.title-image{
  width: 536px;
}
</style>
